<?php

namespace common\models\wechat;

use EasyWeChat\Core\Exception;
use EasyWeChat\Encryption\EncryptionException;
use Yii;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;

/**
 * This is the model class for table "wechat_fans_groups".
 *
 * @property string $id
 * @property string $wid
 * @property string $groups
 */
class WechatFansGroups extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'wechat_fans_groups';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['wid'], 'integer'],
            [['groups'], 'string', 'max' => 10000],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'wid' => '公众号id',
            'groups' => '标签',
        ];
    }



    public static function getFansGroups($force_update = false) {
        $groups = (new Query())->select('groups')->from(WechatFansGroups::tableName())->where(['wid'=>WechatAccounts::WID])->scalar();
        if(!empty($groups) && !$force_update){
            $results = unserialize($groups);
            return $results;
        }
        try{
            $getgroups = Yii::$app->wechat->user_tag->lists();
            $results = ArrayHelper::toArray($getgroups);
            if(empty($groups)){
                Yii::$app->db->createCommand()->insert(WechatFansGroups::tableName(),['wid'=>WechatAccounts::WID,'groups'=>serialize($results)])->execute();
            }else{
                Yii::$app->db->createCommand()
                    ->update(WechatFansGroups::tableName(),['wid'=>WechatAccounts::WID,'groups'=>serialize($results)],'wid=:wid',[':wid'=>WechatAccounts::WID])
                    ->execute();
            }
        }catch (Exception $exception){
            print_r($exception);
        }
        return $results;
    }

    /**
     * @param $name
     * 更新标签
     */
    public function upTags($tagid,$name)
    {

        $result = Yii::$app->wechat->user_tag->update($tagid,$name);
        if($result){
            return $this->getFansGroups(true);
        }
        return false;
    }


    /**
     * @param $name
     * 创建标签
     */
    public function createTags($name)
    {
        $result = Yii::$app->wechat->user_tag->create($name);
        if($result){
            return $this->getFansGroups(true);
        }
        return false;
    }


    /**
     * @param $tagid
     * @return array|bool|mixed
     * 删除标签
     */
    public function deleteTags($tagid)
    {
        $result = Yii::$app->wechat->user_tag->delete($tagid);
        if($result){
            return $this->getFansGroups(true);
        }
        return false;
    }



}
